"use client"

import { View, Text, StyleSheet, TouchableOpacity, Modal, Pressable, Platform, ScrollView, Alert } from "react-native"
import { theme } from "../../constants/theme"
import { X, Volume2 } from "lucide-react-native"
import Animated, { useSharedValue, useAnimatedStyle, withSpring, withTiming } from "react-native-reanimated"
import { useEffect, useState } from "react"
import { LinearGradient } from "expo-linear-gradient"

interface PhoneticSymbol {
    symbol: string
    frequency: number
}

interface WordExample {
    word: string
    phonetic: string
    partOfSpeech: string
    meaning: string
    targetLetter: string
}

interface PhoneticDetailSheetProps {
    visible: boolean
    onClose: () => void
    letter: string
    phoneticData?: {
        totalPronunciations?: number
        phoneticSymbols?: PhoneticSymbol[]
        examples?: WordExample[]
    }
}

export default function PhoneticDetailSheet({ visible, onClose, letter, phoneticData }: PhoneticDetailSheetProps) {
    const translateY = useSharedValue(300)
    const [playingWord, setPlayingWord] = useState<string | null>(null)

    useEffect(() => {
        if (visible) {
            translateY.value = withSpring(0, {
                damping: 20,
                stiffness: 200,
            })
        } else {
            translateY.value = withTiming(300, {
                duration: 250,
            })
        }
    }, [visible])

    const animatedStyle = useAnimatedStyle(() => ({
        transform: [{ translateY: translateY.value }],
    }))

    const playAudio = (word: string) => {
        setPlayingWord(word)
        // Simulate audio playback
        Alert.alert("播放音频", `正在播放: "${word}"`)

        // Reset playing state after 2 seconds
        setTimeout(() => {
            setPlayingWord(null)
        }, 2000)
    }

    if (!phoneticData || !visible) return null

    return (
        <Modal visible={visible} transparent animationType="none" onRequestClose={onClose}>
            <View style={styles.overlay}>
                <Pressable style={styles.backdrop} onPress={onClose} />
                <Animated.View style={[styles.content, animatedStyle]}>
                    {/* Handle bar */}
                    <View style={styles.header}>
                        <View style={styles.handle} />
                    </View>

                    {/* Close button */}
                    <TouchableOpacity style={styles.closeButton} onPress={onClose}>
                        <X size={14} color={theme.colors.neutral.gray} />
                    </TouchableOpacity>

                    <ScrollView
                        style={styles.scrollView}
                        showsVerticalScrollIndicator={false}
                        contentContainerStyle={styles.scrollContent}
                    >
                        {/* Letter and pronunciation count */}
                        <View style={styles.letterHeader}>
                            <Text style={styles.letterTitle}>{letter}</Text>
                            <Text style={styles.pronunciationCount}>
                                在本书单词中，一共有 {phoneticData?.totalPronunciations} 读音
                            </Text>
                        </View>

                        {/* Phonetic Symbols Grid */}
                        <View style={styles.phoneticGrid}>
                            {phoneticData?.phoneticSymbols?.map((item, index) => (
                                <TouchableOpacity
                                    key={index}
                                    style={styles.phoneticItem}
                                    onPress={() => playAudio(item.symbol)}
                                    activeOpacity={0.7}
                                >
                                    <View style={styles.symbolWrapper}>
                                        <Text style={styles.phoneticSymbol}>/{item.symbol}/</Text>
                                        <Volume2 size={10} color={theme.colors.neutral.gray} />
                                    </View>
                                    <Text style={styles.frequency}>({item.frequency})</Text>
                                </TouchableOpacity>
                            ))}
                        </View>

                        {/* Divider */}
                        <View style={styles.divider} />

                        {/* Letter with phonetic */}
                        <View style={styles.letterPhonetic}>
                            <Text style={styles.letterText}>{letter}</Text>
                            <Text style={styles.letterPhoneticSymbol}>/ə/</Text>
                            <Volume2 size={12} color={theme.colors.neutral.gray} />
                        </View>

                        {/* Word Examples */}
                        {phoneticData?.examples?.map((example, index) => (
                            <View key={index} style={styles.exampleItem}>
                                <View style={styles.wordSection}>
                                    <Text style={styles.word}>
                                        {example.word.split("").map((char, i) => (
                                            <Text
                                                key={i}
                                                style={[
                                                    styles.wordChar,
                                                    char.toLowerCase() === example.targetLetter.toLowerCase() && styles.highlightLetter,
                                                ]}
                                            >
                                                {char}
                                            </Text>
                                        ))}
                                    </Text>
                                    <Text style={styles.phonetic}>/{example.phonetic}/</Text>
                                </View>
                                <View style={styles.meaningSection}>
                                    <Text style={styles.partOfSpeech}>{example.partOfSpeech}</Text>
                                    <Text style={styles.meaning}>{example.meaning}</Text>
                                </View>
                            </View>
                        ))}

                        {/* Bottom buttons */}
                        <View style={styles.bottomButtons}>
                            <TouchableOpacity style={styles.secondaryButton} onPress={() => console.log("View more")}>
                                <Text style={styles.secondaryButtonText}>查看更多</Text>
                            </TouchableOpacity>

                            <TouchableOpacity style={styles.primaryButton} onPress={() => console.log("Learn list")}>
                                <LinearGradient
                                    colors={theme.colors.primary.gradient}
                                    start={{ x: 0, y: 0 }}
                                    end={{ x: 1, y: 0 }}
                                    style={styles.gradientButton}
                                >
                                    <Text style={styles.primaryButtonText}>学习此列表</Text>
                                </LinearGradient>
                            </TouchableOpacity>
                        </View>

                        {/* Add some bottom padding for iOS devices */}
                        <View style={{ height: Platform.OS === "ios" ? 16 : 8 }} />
                    </ScrollView>
                </Animated.View>
            </View>
        </Modal>
    )
}

const styles = StyleSheet.create({
    overlay: {
        flex: 1,
        justifyContent: "flex-end",
    },
    backdrop: {
        ...StyleSheet.absoluteFillObject,
        backgroundColor: "rgba(0, 0, 0, 0.3)",
    },
    content: {
        backgroundColor: theme.colors.neutral.white,
        borderTopLeftRadius: theme.borderRadius.large,
        borderTopRightRadius: theme.borderRadius.large,
        height: "80%",
        flexDirection: "column",
    },
    header: {
        alignItems: "center",
        paddingTop: theme.spacing.sm,
        paddingBottom: theme.spacing.xs,
    },
    handle: {
        width: 32,
        height: 4,
        backgroundColor: theme.colors.neutral.lightGray,
        borderRadius: 2,
    },
    closeButton: {
        position: "absolute",
        right: theme.spacing.md,
        top: theme.spacing.sm,
        width: 24,
        height: 24,
        borderRadius: 12,
        backgroundColor: theme.colors.neutral.lightGray,
        alignItems: "center",
        justifyContent: "center",
        zIndex: 10,
    },
    scrollView: {
        flex: 1,
    },
    scrollContent: {
        padding: theme.spacing.md,
        paddingTop: theme.spacing.xs,
    },
    letterHeader: {
        alignItems: "center",
        marginBottom: theme.spacing.sm,
    },
    letterTitle: {
        fontSize: 22,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.neutral.black,
        marginBottom: theme.spacing.xs,
    },
    pronunciationCount: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.darkGray,
    },
    phoneticGrid: {
        flexDirection: "row",
        flexWrap: "wrap",
        backgroundColor: theme.colors.neutral.background,
        borderRadius: theme.borderRadius.medium,
        padding: theme.spacing.sm,
        gap: theme.spacing.xs,
        marginBottom: theme.spacing.sm,
    },
    phoneticItem: {
        alignItems: "center",
        backgroundColor: theme.colors.neutral.white,
        borderRadius: theme.borderRadius.medium,
        padding: theme.spacing.xs,
        width: "18%", // Fit more items per row
        marginBottom: theme.spacing.xs,
    },
    symbolWrapper: {
        flexDirection: "row",
        alignItems: "center",
        gap: 2,
    },
    phoneticSymbol: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.black,
    },
    frequency: {
        fontSize: theme.fontSize.xs,
        color: theme.colors.neutral.gray,
        marginTop: 2,
    },
    divider: {
        height: 1,
        backgroundColor: theme.colors.neutral.lightGray,
        marginVertical: theme.spacing.sm,
    },
    letterPhonetic: {
        flexDirection: "row",
        alignItems: "center",
        marginBottom: theme.spacing.sm,
        gap: theme.spacing.xs,
    },
    letterText: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.neutral.black,
    },
    letterPhoneticSymbol: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.darkGray,
    },
    exampleItem: {
        flexDirection: "row",
        backgroundColor: theme.colors.neutral.white,
        borderRadius: theme.borderRadius.medium,
        marginBottom: theme.spacing.xs,
        overflow: "hidden",
        borderWidth: 1,
        borderColor: theme.colors.neutral.lightGray,
    },
    wordSection: {
        flex: 1,
        padding: theme.spacing.sm,
        backgroundColor: theme.colors.neutral.white,
    },
    word: {
        fontSize: theme.fontSize.md,
        marginBottom: 2,
    },
    wordChar: {
        color: theme.colors.neutral.black,
    },
    highlightLetter: {
        color: theme.colors.primary.default,
    },
    phonetic: {
        fontSize: theme.fontSize.xs,
        color: theme.colors.neutral.darkGray,
    },
    meaningSection: {
        flex: 1,
        padding: theme.spacing.sm,
        backgroundColor: theme.colors.neutral.background,
    },
    partOfSpeech: {
        fontSize: theme.fontSize.xs,
        fontStyle: "italic",
        color: theme.colors.neutral.darkGray,
        marginBottom: 2,
    },
    meaning: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.black,
    },
    bottomButtons: {
        flexDirection: "row",
        padding: theme.spacing.md,
        gap: theme.spacing.md,
        marginTop: theme.spacing.md,
    },
    secondaryButton: {
        flex: 1,
        paddingVertical: theme.spacing.sm,
        borderRadius: theme.borderRadius.large,
        backgroundColor: theme.colors.neutral.lightGray,
        alignItems: "center",
    },
    secondaryButtonText: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.darkGray,
        fontWeight: theme.fontWeight.semiBold,
    },
    primaryButton: {
        flex: 1,
        borderRadius: theme.borderRadius.large,
        overflow: "hidden",
    },
    gradientButton: {
        paddingVertical: theme.spacing.sm,
        alignItems: "center",
    },
    primaryButtonText: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.white,
        fontWeight: theme.fontWeight.semiBold,
    },
})

